package com.begamer.card.controller;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.AES;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.RechargeData;
import com.begamer.card.common.util.binRead.RunnerData;
import com.begamer.card.json.PayBackJson;
import com.begamer.card.json.command2.PayOrderJson;
import com.begamer.card.json.command2.PayOrderResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.pojo.Activity;
import com.begamer.card.model.pojo.Mail;
import com.begamer.card.model.pojo.PayRecord;
import com.begamer.card.model.pojo.SpeciaMail;
import com.begamer.card.model.pojo.ZcMail;

/**
 * 消费回调
 * 
 * @author LiTao 2014-6-16 下午07:04:44
 */
public class ReceivePayController extends AbstractMultiActionController {
	private static final Logger playerlogger = PlayerLogger.logger;
	private static final Logger errorlogger = ErrorLogger.logger;
	private static final Logger logger = Logger.getLogger(ReceivePayController.class);

	@Autowired
	private CommDao commDao;

	public ModelAndView receive_pay(HttpServletRequest request,
			HttpServletResponse response)
	{
		String content = RequestUtil.readParams(request);
		if (content == null || content.trim().length() == 0)
		{
			logger.warn("消息为空");
		}
		else
		{
			try
			{
				byte[] byteDecoded = AES.aesDecryptForPay(
						Cache.getInstance().pay_game_key, Base64
								.decodeBase64(content.getBytes()), 0);
				String contentDecoded = new String(byteDecoded, "utf-8");
				// 解析json
				PayBackJson pb = JSON.toJavaObject(JSON
						.parseObject(contentDecoded), PayBackJson.class);
				int playerId = StringUtil.getInt(pb.playerId);
				int rechargeId = StringUtil.getInt(pb.rechargeId);
				int consumValue = (int) StringUtil.getFloat(pb.consumeValue);
				// 保存支付信息
				PayRecord payRecord = PayRecord.createPayRecord(playerId,
						consumValue, rechargeId);
				commDao.savePayRecord(payRecord);
				// 给玩家添加数据
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(playerId);
				RechargeData rd = RechargeData.getRechargeData(rechargeId);
				if (pi != null && rd != null && consumValue>=rd.cost)
				{
					// 首充奖励邮件：钻石*168 金币*100W 3★气刃乱舞*1(skill) 13031 5★阿波罗*1
					// 35002(card)
					if (pi.player.getFirstPayType()==0)
					{
						// 首次登录邮件
						List<ZcMail> zms = commDao.findUseZcMail(2);
						if (zms != null & zms.size() > 0)
						{
							for (ZcMail zcMail : zms)
							{
								Mail mail = Mail.createMail(pi.player.getId(),
										"GM", zcMail.getTitle(), zcMail
												.getContent(), zcMail
												.getReward1(), zcMail
												.getReward2(), zcMail
												.getReward3(), zcMail
												.getReward4(), zcMail
												.getReward5(), zcMail
												.getReward6(),
										zcMail.getGold(), zcMail.getCrystal(),
										zcMail.getRuneNum(), zcMail.getPower(),
										zcMail.getFriendNum(), zcMail
												.getDeleteTime());
								Cache.getInstance().sendMail(mail);
							}
						}
						// Mail mail = Mail.createMail(pi.player.getId(),
						// "GM","首充奖励", "", "4&13031&1", "3&35002&1", "", "","",
						// "", 1000000, 168, 0, 0, 0,Constant.MailKeepTime1);
						pi.player.setFirstPayType(1);
					}
					pi.player.addVipCost(consumValue);
					// 直接获取钻石
					if (rd.type == 1)
					{
						pi.player.addCrystalPay(rd.crystal);
						Activity a =Cache.getInstance().getActivityById(6);//聚宝盆
						if(a!=null && a.getSttime() !=null && a.getEndtime() !=null && a.getSttime().length()>0 && a.getEndtime().length()>0)
						{
							String date=StringUtil.getDate(System.currentTimeMillis());
							if(date.compareTo(a.getSttime())>=0 && date.compareTo(a.getEndtime())<=0)
							{
								pi.player.setCornucopiaCrystal(pi.player.getCornucopiaCrystal()+rd.crystal);
							}
						}
						// 购买的物品为首次购买双倍
						if (rd.double1 == 1)
						{
							String rechargeInfo = pi.player.getRechargeInfo();
							if (rechargeInfo == null || "".equals(rechargeId))
							{
								rechargeInfo = rechargeId + "";
								playerlogger.info("|区服："
										+ Cache.getInstance().serverId + "|玩家："
										+ playerId + "|" + rechargeId
										+ "|首次购买双倍赠送");
								pi.player.addCrystal(rd.crystal);
								pi.player.setRechargeInfo(rechargeInfo);
							}
							else
							{
								boolean contain = false;
								String[] ss = rechargeInfo.split("-");
								for (String s : ss)
								{
									if (s.equals(rechargeId + ""))
									{
										contain = true;
										break;
									}
								}
								if (!contain)
								{
									rechargeInfo += "-" + rechargeId;
									playerlogger.info("|区服："
											+ Cache.getInstance().serverId
											+ "|玩家：" + playerId + "|"
											+ rechargeId + "|首次购买双倍赠送");
									pi.player.addCrystal(rd.crystal);
									pi.player.setRechargeInfo(rechargeInfo);
								}
							}
						}
					}
					// 月卡
					else if (rd.type == 2)
					{
						pi.player.setVipMonthType(1);
						pi.player.addVipMonthDay(30);
					}
					// 不在线的保存一下
					if (Cache.getInstance().getPlayerInfoByMemory(
							pi.player.getId()) == null)
					{
						commDao.savePlayerInfo(pi);
					}
					playerlogger.info("|区服：" + Cache.getInstance().serverId
							+ "|玩家：" + pi.player.getId() + "|"
							+ pi.player.getName() + "|等级："
							+ pi.player.getLevel() + "|消费成功|" + rd.id + "|"
							+ rd.name);
					//累计充值nRMB发奖励
					timeQuantumTotalPayActivity(pi.player.getId(), payRecord.getId());
					//单笔充值nRMB发奖励
					timeQuantumOnePayActivity(pi.player.getId(), payRecord.getCost());
					//如果大风车活动正在进行。则根据充值金额反馈给玩家抽奖次数
					Activity a=Cache.getInstance().getActivityById(8);
					if(a.getSttime() !=null && a.getEndtime()!=null && a.getSttime().length()>0 && a.getEndtime().length()>0)
					{
						if(StringUtil.getDateTime(System.currentTimeMillis()).compareTo(a.getEndtime())<0 && StringUtil.getDateTime(System.currentTimeMillis()).compareTo(a.getSttime())>0)
						{
							List<RunnerData> rDatas =RunnerData.getDatasByType(1);
							RunnerData rData =rDatas.get(rDatas.size()-1);
							if(rData.condition<payRecord.getCost())//如果充值金额大于最大档位值，则按照最大档位值重复计算，
							{
								int times =payRecord.getCost()/rData.condition;
								for(int i=0;i<times;i++)
								{
									pi.player.addLottoTimes(1, rData.condition);
								}
							}
							else//否则。正常计算
							{
								pi.player.addLottoTimes(1, payRecord.getCost());
							}
						}
					}
				}
				else
				{
					playerlogger.info("|区服：" + Cache.getInstance().serverId
							+ "|玩家：" + playerId + "|" + rechargeId + "|金额:"+consumValue+"|消费失败");
				}
			}
			catch (Exception e)
			{
				errorlogger.error("解密消费信息出错", e);
			}
		}
		RequestUtil.setResult(request, "success");
		return new ModelAndView("/user/result.vm");
	}

	/** 获取游戏的支付订单* */
	public ModelAndView get_pay_order(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			/**
			 * *********************************修改部分
			 * start***********************************
			 */
			// 获取参数
			PayOrderJson rj = JSONObject.toJavaObject(jsonObject,
					PayOrderJson.class);
			PayOrderResultJson srj = new PayOrderResultJson();
			// 获取请求的数据
			PlayerInfo pi = Cache.getInstance().getPlayerInfo(rj.getPlayerId(),
					request.getSession());
			if (pi != null)
			{
				int order = 0;
				try
				{
					String serverUrl = Cache.getInstance().pay_order_url;
					PostMethod req = new PostMethod(serverUrl);
					req.getParams().setParameter(
							HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");// 设置参数字符集
					req.setParameter("consumValue", rj.consumValue);
					req.setParameter("extra", rj.extra);
					req.setParameter("serverId", Cache.getInstance().serverId
							+ "");
					req.setParameter("playerId", rj.playerId + "");
					req.setParameter("userId", "");
					HttpClient httpclient = new HttpClient();
					int result = httpclient.executeMethod(req);
					if (result == 200)
					{
						InputStream inputStream = req.getResponseBodyAsStream();
						byte[] resBytes = new byte[0];
						byte[] buff = new byte[256];
						int n = 0;
						while ((n = inputStream.read(buff)) >= 0)
						{
							int length = resBytes.length;
							byte[] bs = new byte[length + n];
							System.arraycopy(resBytes, 0, bs, 0, length);
							System.arraycopy(buff, 0, bs, length, n);
							resBytes = bs;
						}
						inputStream.close();
						String msg = new String(resBytes, Charset
								.forName("UTF-8"));
						order = StringUtil.getInt(msg);
					}
					req.releaseConnection();
				}
				catch (Exception e)
				{
					errorlogger.error("请求订单号出错", e);
				}
				srj.order = order;
				srj.consumValue = rj.consumValue;
				srj.extra = rj.extra;
				srj.serverId = Cache.getInstance().serverId + "";
				srj.playerId = rj.playerId + "";
				srj.userId = "";
				playerlogger.info("|区服：" + Cache.getInstance().serverId
						+ "|玩家：" + pi.player.getId() + "|"
						+ pi.player.getName() + "|等级：" + pi.player.getLevel()
						+ "|请求支付订单号|" + order);
			}
			else
			{
				srj.errorCode = -3;
			}
			Cache.recordRequestNum(srj);
			String msg = JSON.toJSONString(srj);
			/**
			 * *********************************修改部分end*************************************
			 */
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	// 累计充值返利活动
	private void timeQuantumTotalPayActivity(int playerId, int excetPayRecordId)
	{
		List<SpeciaMail> speciaMails = commDao.getSpeciaMails(3);
		if (speciaMails != null && speciaMails.size() > 0)
		{
			long curTime = System.currentTimeMillis();
			for (int k = 0; k < speciaMails.size(); k++)
			{
				SpeciaMail speciaMail1 = speciaMails.get(k);
				if (speciaMail1.isTrue(curTime))
				{
					int payToal = commDao.getPayTotal(playerId, speciaMail1
							.getBeginTime(), speciaMail1.getEndTime(), 0);
					int prePayNums = commDao.getPayTotal(playerId, speciaMail1
							.getBeginTime(), speciaMail1.getEndTime(),
							excetPayRecordId);
					if (payToal >= speciaMail1.getValue()
							&& prePayNums < speciaMail1.getValue())
					{
						Mail mail = Mail.createMail(playerId, "GM", speciaMail1
								.getTitle(), speciaMail1.getContent(),
								speciaMail1.getReward1(), speciaMail1
										.getReward2(),
								speciaMail1.getReward3(), speciaMail1
										.getReward4(),
								speciaMail1.getReward5(), speciaMail1
										.getReward6(), speciaMail1.getGold(),
								speciaMail1.getCrystal(), speciaMail1
										.getRuneNum(), speciaMail1.getPower(),
								speciaMail1.getFriendNum(), speciaMail1
										.getDeleteTime());
						Cache.getInstance().sendMail(mail);
						playerlogger.info("|区服：" + Cache.getInstance().serverId
								+ "|玩家：" + playerId + "|获得累计充值"
								+ speciaMail1.getValue() + "RMB,返利邮件");
					}
				}
			}
		}
	}

	// 单笔充值返利活动
	private void timeQuantumOnePayActivity(int playerId, int cost)
	{
		List<SpeciaMail> speciaMails = commDao.getSpeciaMails(4);
		if (speciaMails != null && speciaMails.size() > 0)
		{
			long curTime = System.currentTimeMillis();
			for (int k = 0; k < speciaMails.size(); k++)
			{
				SpeciaMail speciaMail1 = speciaMails.get(k);
				if (speciaMail1.isTrue(curTime))
				{
					if (cost >= speciaMail1.getValue())
					{
						Mail mail = Mail.createMail(playerId, "GM", speciaMail1
								.getTitle(), speciaMail1.getContent(),
								speciaMail1.getReward1(), speciaMail1
										.getReward2(),
								speciaMail1.getReward3(), speciaMail1
										.getReward4(),
								speciaMail1.getReward5(), speciaMail1
										.getReward6(), speciaMail1.getGold(),
								speciaMail1.getCrystal(), speciaMail1
										.getRuneNum(), speciaMail1.getPower(),
								speciaMail1.getFriendNum(), speciaMail1
										.getDeleteTime());
						Cache.getInstance().sendMail(mail);
						playerlogger.info("|区服：" + Cache.getInstance().serverId
								+ "|玩家：" + playerId + "|获得单笔充值"
								+ speciaMail1.getValue() + "RMB,返利邮件");
					}
				}
			}
		}
	}
}
